<script setup>
	import { computed, ref,watch  } from 'vue'
	import { onLoad,onShareAppMessage } from '@dcloudio/uni-app'
 	import leisureModal from './components/leisureModal.vue'
	import leisureAdd from './components/leisureAdd.vue'
	import leisureEdit from './components/leisureEdit.vue'
	import end from './components/end.vue'
	import set from './components/set.vue'
	import myAlert from './components/alert.vue'
	import editSet from './components/editSet.vue'
	import { reduceFun,totalFun,discrepancyFun,endCurrent } from '@/utils/reduceFun.js'
	import { store } from '@/uni_modules/uni-id-pages/common/store.js'
	
	const userId = computed(() => store.userInfo._id)
	const db = uniCloud.database()
	const list = ref({})
	const _id = ref('')
	const fraction = uniCloud.importObject('addFraction')
	const leisureModalRef = ref()
	const setShow = ref(false)
	const editSetRef = ref()
	
	// 是否登录，否则跳转登录
	// 是否已经邀请在对局，添加到对局中
	
	onLoad(async (options) => {
		// 分享进来的id 存储到本地
		if(options.id){
			await uni.setStorageSync('leisureId',options.id)
			const token = await uni.getStorageSync('uni_id_token')
			if(token){
				await fraction.updateUserID(options.id,userId.value)
				const res = await db.collection('leisure_list').where({
					_id:options.id
				}).get()
				changeData(res)
			}else{
				uni.navigateTo({
					url:`/uni_modules/uni-id-pages/pages/login/login-withoutpwd`
				})
			}
		}else{
			getData()
		}
	})
	
	onShareAppMessage(() => {
		const { nameList,_id } = list.value
		return {
			title:nameList.join('-'),
			path:`/pages/index/leisure?id=${_id}`,
			desc:"星期天"
		}
	})
	
	// 获取是否有未结束的数据
	const getData = async () => {
		const res = await db.collection('leisure_list').where({
			userId:db.command.in([userId.value]),
			status:0
		}).get()
		changeData(res)
	}
	
	// 处理数据
	const changeData = (res) => {
		const { data } = res.result
		if(!data.length){
			return leisureModalRef.value.show = true
		} 
		list.value = data[0]
		_id.value = data[0]._id
	}
	
	// 创建房间
	const changeCreateRoom = async (id) => {
		_id.value = id
		await updateData()
		setShow.value = true
	}
	// 更细数据
	const updateData = async () => {
		const res = await db.collection('leisure_list').where({_id:_id.value}).get()
		list.value = res.result.data[0]
	}

	watch(
		() => list.value.currentData,
		async (newValue) => {
			const arr = reduceFun(newValue)
			const hasEqualTo = arr.some(num => num >= 100)
			if(hasEqualTo){
				await fraction.editCurrent(_id.value)
				const newArr = arr.map(item => Math.round(item / 10) * 10)
				await fraction.addHistory(_id.value,[[...newArr],...newValue])
				updateData()
			}
		}
	)
	
	// 计算总和
	const totalNum = computed(() => {
		const { dataList,nameList } = list.value
		if(!nameList) return ''
		let totalList = nameList.map(item => ({
			name: item,
			total: 0,
			num: 0
		}))
		if(dataList.length){
			const totalNumberArr = totalFun(dataList)
			const discrepancyNumArr = discrepancyFun(totalNumberArr)
			totalList = totalList.map((item, index) => ({
			  ...item,
			  total: totalNumberArr[index],
			  num:discrepancyNumArr[index]
			}))
		}
		return totalList
	})
	
	// 新增对局加分
	const addShow = ref(false)
	const changeAdd = () => {
		addShow.value = true
	}
	const updateDate = async (val) => {
		const res = await fraction.addCurrent(_id.value,val)
		addShow.value = false
		updateData()
	}

	// 结束对局
	const endRef = ref()
	const handlerEnd = async () => {
		const { currentData } = list.value
		if(currentData.length){
			const endData = reduceFun(currentData)
			const newEndArr = endData.map(item => Math.round(item / 10) * 10)
			await fraction.endCurrent(_id.value,[[...newEndArr],...currentData])
		}else{
			await fraction.endCurrentData(_id.value)
		}
		updateData()
		endRef.value.show = false
	}

	// 编辑数据
	const eidtShow = ref(false)
	const editIndex = ref(0)
	const changeEdit = (index) => {
		editIndex.value = index
		eidtShow.value = true
	}
	const editUpdata = async (val) => {
		await fraction.editData(_id.value,editIndex.value,val)
		eidtShow.value = false
		updateData()
	}
	
	// 设置牌的倍数
	const setCancel = () => {
		setShow.value = false
		editSetRef.value.eidtSetShow = true
	}
	
	// 计算当前局的数量
	const currentNum = computed(() => {
		const {nameList,currentData} = list.value
		if(currentData && currentData.length) {
			const  currentTotalNum  = reduceFun(currentData)
			const newNameArray = []
			nameList.forEach((item,index) => {
				newNameArray.push({name:item,num:currentTotalNum[index]})
			})
			return newNameArray
		}else{
			const currentNameList = []
			nameList && nameList.forEach(item => {
				currentNameList.push({name:item,num:''})
			})
			return currentNameList
		}
	})
</script>

<template>
	<view class="content">
		<view class="header_content">
			<view class="total flex">
				<view class="flex" v-for="item in totalNum" :key="item.name" style="flex-direction: column;">
					<view>
						{{item.name}}<text style="font-size: 30rpx;">({{item.total}})</text>
					</view>
					<view :class="item.num > 0 ? 'active' :item.num < 0 ? 'error' : ''">{{item.num}}</view>
				</view>
			</view>
			<view class="flex name_content">
				<text class="flex left">姓名:</text>
				<view class="name_list flex">
					<view class="name_item flex" style="flex-direction: column;" v-for="(item,index) in currentNum" :key="item">
						<text>{{item.name}}</text>
						<text style="font-size: 26rpx;">{{item.num}}</text>
					</view>
				</view>
			</view>
		</view>
		<scroll-view class="scroll-view" scroll-y>
			<view class="flex current_list" v-for="(item,index) in list.currentData" :key="index" @click.stop="changeEdit(index)">
				<view class="left flex">{{index + 1}}</view>
				<view class="number_list">
					<text class="name_item flex"
						:class="{active:val == '0'}" v-for="(val,key) in item" :key="key">
						{{val == '0' ? '—' : val}}
					</text>
				</view>
			</view>
			<view class="history">
				<view class="history_content" v-for="(historyItem,historyInde) in list.dataList" :key="historyItem">
					<view class="title">第{{historyInde + 1}}局</view>
					<view class="container" v-for="(listItem,listIndex) in historyItem" :key="historyInde">
						<view class="left flex">
							{{ listIndex === 0 ? '结算' : listIndex}}
						</view>
						<view class="history_list flex">
							<view class="history_item flex" :class="{active:listIndex == '0'}" v-for="(item,ind) in listItem" :key="ind">
								{{(item == '0' && listIndex != 0)  ? '—' : item}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
	<leisureModal ref="leisureModalRef" @changeCreateRoom="changeCreateRoom" />
	<template v-if="list.status === 0">
		<view class="add flex" @click="changeAdd"> + </view>
		<end ref="endRef" @changeEnd="handlerEnd" />
		<set @handlerSet="setShow = true" />
	</template>
	<template v-if="addShow">
		<leisureAdd :nameList="list.nameList" :numberList="list.scaleNulberList" :scaleList="list.scaleList"
		 @colseModal="addShow = false" @updateDate="updateDate" />
	</template>
	<template v-if="eidtShow">
		<leisureEdit :nameList="list.nameList"  :numberList="list.scaleNulberList" :scaleList="list.scaleList" 
		 @colseModal="eidtShow = false" @editUpdata="editUpdata" />
	</template>
	<template v-if="setShow">
		<myAlert :scaleList="list.scaleNulberList" :scaleArray="list.scaleList" 
		@setCancel="setCancel" @handlerConfirmSeet="setShow = false" />
	</template>
	<editSet ref="editSetRef" :id="_id"  @changeSetScale="updateData()" />
</template>

<style lang="scss">
	$bg-color:rgba(92, 211, 194,0.6);
	.content{
		height: 100vh;
		.header_content{
			position: sticky;
			top: 0;
			.total{
				height: 120rpx;
				padding: 0 20rpx;
				justify-content: space-around;
				font-size: 34rpx;
			}
			.left_name{
				height: 100%;
				flex: 1;
				justify-content: space-between;
			}
		}
		.name_content{
			justify-content: space-between;
			height: 100rpx;
			.name_list{
				justify-content: space-around;
				flex: 1;
				height: 100%;
			}
			.name_item{
				background: $bg-color;
				color: #fff;
				width: 100%;
				height: 100%;
			}
		}
		.scroll-view{
			height: calc(100vh - 210rpx);
			.current_list{
				justify-content: space-between;
				height: 100rpx;
			}
			.number_list{
				display: grid;
				 grid-template-columns: repeat(4, 1fr); 
				 flex: 1;
				height: 100%;
				border-bottom: 1rpx solid #eee;
			}
		}
	}
	.left{
		width: 120rpx;
		height: 100rpx;
		background: $bg-color;
		color: #fff;
	}
	.active{
		color: #5CD5C6;
		font-weight: 700;
	}
	.error{
		color: #f00;
		font-weight: 700;
	}
	.add{
		position: fixed;
		right: 10rpx;
		bottom: 26%;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: $bg-color;
		color: #fff;
		font-size: 60rpx;
		line-height: 0;
		z-index: 99999;
	}
	.history{
		.title{
			color: #5CD5C6;
			font-weight: 700;
			padding: 0 20rpx;
		}
		&_list{
			justify-content: space-around;
			flex: 1;
		}
		&_item{
			flex: 1;
			height: 100rpx;
			border-bottom: 1rpx solid #eee;
		}
		.container{
			display: flex;
			justify-content: space-between;
		}
	}
</style>